package org.videopractice.network;

import org.videopractice.common.Logger;

import java.io.Serializable;
import java.net.InetSocketAddress;

import io.netty.channel.Channel;

public class IoSession implements Serializable {

    // 序列化版本号
    private static final long serialVersionUID = 1L;

    /** 连接CHANNEL **/
    public final Channel channel;

    /** ip地址 **/
    public final String ipAddress;

//    /** 端口 **/
//    private final int port;

    /** 账号 **/
    private String account;

    /** 是否重连 **/
    private boolean reconnected = false;

    /**************************************************************************/

    public IoSession(Channel channel) {
        this.channel = channel;
        this.ipAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().toString().substring(1);
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getAccount() {
        return account;
    }

    public void setReconnected(boolean reconnected) {
        this.reconnected = reconnected;
    }

    public boolean isReconnected() {
        return reconnected;
    }

    public boolean isLogin() {
        // 暂时没有登陆，所以如果链接过就算登陆了。
        return reconnected;
    }



    /**
     * 判断通道是否关闭
     * @return true 关闭 false 激活
     */
    public boolean isClose() {
        if (channel == null) {
            return true;
        }
        return !channel.isActive() || !channel.isOpen();
    }

    /**
     * 关闭session
     */
    public void close() {
//        isLogin = Boolean.FALSE;
        try {
            if (this.channel == null) {
                return;
            }
            if (channel.isOpen()) {
                channel.close();
            }
        } catch (Exception e) {
            Logger.e("Close session[" + this + "] error");
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("IoSession [channel=").append(channel)
                .append(", ipAddress=").append(ipAddress)
                .append(", account=").append(account)
                .append(", reconnected=").append(reconnected).append("]");
        return builder.toString();
    }
}
